package com.atwisdom.star.service.equipment.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.atwisdom.star.common.util.JsonUtil;
import com.atwisdom.star.common.vo.JsonResult;
import com.atwisdom.star.common.vo.ResultInfo;
import com.atwisdom.star.core.dsl.modelClass.hier.Impl.HierInstanceDslServiceImpl;
import com.atwisdom.star.core.dsl.modelClass.logic.Impl.LogicInstanceDslServiceImpl;
import com.atwisdom.star.core.dsl.modelClass.resource.Impl.ResourceInstanceDslServiceImpl;
import com.atwisdom.star.exception.pojo.BusinessException;
import com.atwisdom.star.service.business.LogicLogic;
import com.atwisdom.star.service.business.LogicResource;
import com.atwisdom.star.service.equipment.CheckInspectionService;
import com.atwisdom.star.service.util.LogicUtil;
import com.atwisdom.star.service.util.ResourceUtil;
import com.atwisdom.star.service.util.ValidateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @ClassName: InspectionServiceImpl
 * @ Description:
 * @author:王红艳
 * @date:
 */
@Service
public class CheckInspectionServiceImpl implements CheckInspectionService {

    @Autowired
    private LogicUtil logicUtil;

    @Autowired
    private LogicInstanceDslServiceImpl logicInstanceDslServiceImpl;

    @Autowired
    private HierInstanceDslServiceImpl hierInstanceDslServiceImpl;

    @Autowired
    private ResourceInstanceDslServiceImpl resourceInstanceDslService;

    @Autowired
    ResourceUtil resourceUtil;

    private final String CLASS_NAME_EQUIPMENT = "EquipmentCheck";
    private final String CLASS_NAME_PLAN = "EquipmentCheckPlan";
    private final String TYPE = "logic";
    private final String CLASS_NAME_KNOWLEDGE = "knowledge";
    private final String CLASS_NAME_KNOWLEDGE_TYPE = "inspection";

    private LogicLogic getLogicLogic(){
//        return new LogicLogic(logicUtil,resourceUtil,logicInstanceDslServiceImpl,logicInstanceDslServiceImpl,hierInstanceDslServiceImpl);
        return new LogicLogic();
    }

    private LogicResource getLogicResource(){
//        return new LogicResource(logicUtil,resourceUtil,logicInstanceDslServiceImpl,resourceInstanceDslService,hierInstanceDslServiceImpl);
        return new LogicResource();
    }
    /**
     * 根据设备ID查询设备模板存在则查询返回，不存在则新增返回
     * @param data
     * @throws BusinessException
     */
    @Override
    @Transactional
    public ResultInfo<?> queryEquipmentTemByEquId(JSONObject data)  throws BusinessException {
        int id = data.getIntValue("id");
        if(null==data.get("id")){
            return JsonResult.error(500,"id不能为空");
        }
        JSONObject values = JsonUtil.buildJson(new Object[] {"if_equ",id,"sf_name",data.getString("sf_name"),"sf_code",data.getString("sf_code"),"bf_template",true});
        return JsonResult.success(logicUtil.queryUpdateOrAdd(CLASS_NAME_EQUIPMENT,TYPE,values,"if_equ","bf_template"));
    }

    /**
     * 复制巡检计划，返回复制的模板实例
     * @param data
     * @return
     * @throws BusinessException
     */
    @Override
    @Transactional
    public ResultInfo<?> executePlan(JSONObject data)  throws BusinessException {
        ValidateUtil.hasEmpty(data.get("id"));//校验参数
        LogicLogic logicLogic = getLogicLogic();
        logicLogic.setTemplate(data.getLong("id"));
        JSONObject copyPlan = logicLogic.copyContainerFromTemplate();
        List<JSONObject> copyEquList = logicLogic.copyHierFromTemplate(copyPlan);
        copyEquList.forEach(copyEqu->{
            Long templateId = copyEqu.getJSONObject("values").getLong("if_template");
            LogicResource logicResource = getLogicResource();
            logicResource.setTemplate(templateId);
            logicResource.copyHierFromTemplate(copyEqu);
        });
        return JsonResult.success(copyPlan);
    }

    /**
     * 报工
     * @param data 报工参数
     * @return 报工数据
     * @throws BusinessException
     */
    @Override
    @Transactional
    public ResultInfo<?> workReport(JSONObject data)  throws BusinessException {
        ValidateUtil.hasEmpty(data.get("executeArray"),data.get("executeJson"));
        List<JSONObject> executeArray = data.getJSONArray("executeArray").toJavaList(JSONObject.class);
        if(CollectionUtil.isNotEmpty(executeArray)) {
            resourceInstanceDslService.updateByIds(executeArray);
        }
         return JsonResult.success(logicInstanceDslServiceImpl.updateById(data.getJSONObject("executeJson")));
    }

    /**
     * 加入知识库
     * @param data 知识库数据
     * @return 报工数据
     * @throws BusinessException
     */
    @Override
    @Transactional
    public ResultInfo<?> addKnowledge(JSONObject data)  throws BusinessException {
        JSONObject values = data.getJSONObject("values");
        values.putAll(JsonUtil.buildJson(new Object[]{"linkId",JsonUtil.get(data,"id"),"linkClassName",JsonUtil.get(data,"className"),"linkType",JsonUtil.get(data,"type")}));
        resourceUtil.queryUpdateOrAdd(CLASS_NAME_KNOWLEDGE,CLASS_NAME_KNOWLEDGE_TYPE,values,"linkId","linkClassName","linkType");
        return JsonResult.success(logicInstanceDslServiceImpl.updateById(data));
    }

    /**
     * 审批计划
     * data示例：{"pointer":{"className":"","type":"","id":""},"approveValues":{"operatorId":"","operatorName":"","operateTime":"","action":"","status":"","opinions":""}}
     * @param data
     * @return
     * @throws BusinessException
     */
    @Override
    @Transactional
    public ResultInfo<?> approvePlan(JSONObject data)  throws BusinessException {
        ValidateUtil.hasEmpty(data.getJSONObject("pointer"),data.getJSONObject("approveValues"));//校验参数
        JSONObject approveValues = data.getJSONObject("approveValues");
        ValidateUtil.hasEmpty(approveValues.get("operatorId"),approveValues.get("operatorName"),approveValues.get("operateTime"),approveValues.get("action"),approveValues.get("status"),approveValues.get("opinions"));//校验参数
        JSONObject pointer = data.getJSONObject("pointer");
        ValidateUtil.hasEmpty(data.get("id"),data.get("className"),data.get("type"));//校验参数
        JSONObject values = JsonUtil.buildJson(new Object[] {"bf_template",true,"sf_status",approveValues.getString("status"),"if_approver",approveValues.getIntValue("operatorId"),"sf_approverName",approveValues.getString("operatorName"),"tf_approveTime",approveValues.getString("operateTime"),"tf_approveTime",approveValues.getString("operateTime"),"approveOpinions",approveValues.getString("opinions")});
        logicUtil.addHier("3yhfsk2y0i8000",Long.valueOf(pointer.getString("id")),null,approveValues);
        return JsonResult.success(logicInstanceDslServiceImpl.updateById(JsonUtil.buildJson(new Object[]{"id",Long.valueOf(pointer.getString("id")),"className",pointer.getString("className"),"type",pointer.getString("type"),"values",values})));
    }

}
